<template>
    <div class="app-container">
      <!-- 表单部分 -->
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
        <!-- 各个表单项 -->
        <el-form-item label="订单编号" prop="stoProId">
          <el-input v-model="queryParams.search.stoProId" placeholder="请输入订单编号" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="状态" prop="stoState">
          <el-input v-model="queryParams.search.stoState" placeholder="请输入订单状态" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
  
      <!-- 按钮行 -->
      <!-- <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDeleteAll">删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row> -->
  
      <!-- 表格展示 -->
      <el-table v-loading="loading" :data="salesOrderList" @selection-change="handleSelectionChange" type="selection" show-row-hover selection-mode="multiple" header-cell-class-name="custom-checkbox-header">
        <!-- 复选框列 -->
        <!-- <el-table-column type="selection" width="50"></el-table-column> -->
        <!-- 各列定义 -->
        <el-table-column prop="stoProId" label="订单编号"></el-table-column>
        <el-table-column prop="stoSupId" label="供应商"></el-table-column>

        <el-table-column prop="orderDetail.purchaseQuantity" label="采购数量"></el-table-column>
        <el-table-column prop="orderDetail.purchaseUnitPrice" label="采购单价"></el-table-column>
        <el-table-column label="总价">
          <template #default="scope">
            {{ calculateTotalPrice(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column prop="stoPay" label="支付类型"></el-table-column>
        <el-table-column prop="stoDate" label="进货时间"></el-table-column>
        <el-table-column prop="stoState" label="状态">
          <template #default="scope">
            {{ convertOrderState(scope.row.stoState) }}
          </template>
        </el-table-column>
        
        <!-- <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button type="text" icon="Edit" @click="handleUpdateRow(scope.row)">修改</el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button type="text" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
            </el-tooltip>
          </template>
        </el-table-column> -->
      </el-table>
  
      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination class="pagiantion" @current-change="handleCurrentChange" :current-page="queryParams.page" :page-size="queryParams.count" layout="total, prev, pager, next, jumper" :total="queryParams.total">
        </el-pagination>
      </div>
  
      <!-- 添加或修改出库单对话框 -->
      <!-- <el-dialog :title="title" v-model="open" append-to-body v-if="open">
        <el-form ref="inventoryRef" :model="form" :rules="rules" label-width="100px"> -->
          <!-- 表单行 -->
          <!-- <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="库存编号" prop="inventoryId">
                <el-input v-model="form.inventoryId" placeholder="请输入库存编号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商品编号" prop="productId">
                <el-input v-model="form.productId" placeholder="请输入商品编号" />
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="包装类型" prop="packageType">
                <el-input v-model="form.packageType" placeholder="请输入包装类型" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="进货单价" prop="unitPurchasePrice">
                <el-input v-model="form.unitPurchasePrice" placeholder="请输入进货单价" />
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="库存数量" prop="inventoryQuantity">
                <el-input v-model="form.inventoryQuantity" placeholder="请输入库存数量" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出库单编号" prop="outboundEntryId">
                <el-input v-model="form.outboundEntryId" placeholder="请输入出库单编号" />
              </el-form-item>
            </el-col>
          </el-row>
  
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitForm('inventoryRef')">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
      </el-dialog> -->
    </div>
  </template>
  
  
  <script setup name="Inventory">
  import { listSalesOrder } from "@/api/finance/salesorder";
  import { getCurrentInstance, nextTick, reactive, ref } from "vue";
  
  const { proxy } = getCurrentInstance();
  const inventoryList = ref([]);
  const salesOrderList = ref([]);
  const open = ref(false);
  const openTwo = ref(false);
  const openThird = ref(false);
  const loading = ref(true);
  const showSearch = ref(true);
  const title = ref("");
  const titleTwo = ref("");
  const titleThird = ref("");
  const isExpandAll = ref(true);
  const refreshTable = ref(true);
  const stockAlertDialogVisible = ref(false);
  
  // 添加一个响应式变量来存储选中的库存单记录
  const selectedInventoryIds = reactive([]);
  
  const data = reactive({
    form: {
  
    },
    queryParams: {
      page: 1,
      total: 10,
      count: 5,
      search: {
        stoProId: undefined,
        stoState: undefined

      }
    },
    rules: {
  
    },
    totalPrice: 0
  });
  
  const { queryParams, form, rules } = toRefs(data);
  
  // 查询库存列表
  function getList() {
    loading.value = true;
    listSalesOrder(queryParams.value).then(response => {
      salesOrderList.value = response.data.list;
      queryParams.value.page = response.data.current;
      queryParams.value.total = response.data.total;
      loading.value = false;
    }).catch(() => {
      // 请求失败时将 queryParams.page 传上去重新请求
      queryParams.value.page = queryParams.page;
    });
  }
  
  // 切换页码
  function handleCurrentChange(currentPage) {
    queryParams.value.page = currentPage;
    getList();
  }

  // 转换订单状态
  function convertOrderState(stateNumber) {
  switch (stateNumber) {
    case 1:
      return '未完成';
    case 2:
      return '已完成';
    default:
      return '未知状态';
  }
}

  // 取消按钮
  function cancel() {
    open.value = false;
    reset();
  }
  
  function cancelThird() {
    openThird.value = false;
    queryParams.value.page = 1;
  }
  
  function cancelTwo() {
    openTwo.value = false;
  }
  
  // 表单重置
  function reset() {
    form.value = {
      inventoryId: null,
      productId: null,
      packageType: null,
      unitPurchasePrice: null,
      inventoryQuantity: null,
      outboundEntryId: null
    };
    proxy.resetForm("inventoryRef");
  }
  
  // 搜索按钮操作
  function handleQuery() {
    queryParams.value.page = queryParams.value.page || 1;
    getList();
  }
  
  // 重置按钮操作
  function resetQuery() {
    proxy.resetForm("queryRef");
    queryParams.value.search.stoProId = undefined;
    queryParams.value.search.stoState = undefined;
    handleQuery();
  }
  
  // 新增库存按钮操作
  function handleAdd() {
    reset();
    data.form.isNew = true;
    open.value = true;
    title.value = "添加库存";
  }
  
  // 删除单个按钮操作
  function handleDelete(row) {
    proxy.$modal.confirm('是否确认删除名称为"' + row.inventoryId + '"的数据项?').then(function () {
      return delInventory(row.inventoryId);
    }).then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
      // 更新选中记录数组
      selectedInventoryIds.splice(selectedInventoryIds.indexOf(row), 1);
    }).catch(() => { });
  }
  
  // 删除多个按钮操作
  function handleDeleteAll() {
    const idsToDelete = selectedInventoryIds.map(item => item.inventoryId);
    if (idsToDelete.length === 0) {
      proxy.$modal.msgWarning('请先选择要删除的库存单');
      return;
    }
    proxy.$modal.confirm('是否确认删除选中的 ' + idsToDelete.length + ' 个库存单数据项?').then(function () {
      return Promise.all(idsToDelete.map(id => delInventory(id)));
    }).then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
      // 清空选中记录数组
      selectedInventoryIds.length = 0;
    }).catch(() => { });
  }
  
  // 添加或修改按钮操作
  function submitForm(formName) {
    if (formName === 'inventoryRef') {
      // 提交或修改库存表单
      proxy.$refs.inventoryRef.validate((valid) => {
        if (valid) {
          if (data.form.isNew) {
            // 新增库存逻辑
            addInventory(data.form).then(() => {
              proxy.$modal.msgSuccess('新增成功');
              open.value = false;
              getList();
            }).catch((error) => {
              console.error('新增失败：', error);
              proxy.$modal.msgError('新增失败：' + error.message);
            });
          } else {
            // 修改库存逻辑
            updateInventory(data.form).then(() => {
              proxy.$modal.msgSuccess('修改成功');
              open.value = false;
              getList();
            }).catch((error) => {
              console.error('修改失败：', error);
              proxy.$modal.msgError('修改失败：' + error.message);
            });
          }
        } else {
          console.error('表单验证不通过，请检查输入内容');
          proxy.$modal.msgError('表单验证不通过，请检查输入内容');
        }
      });
    }
  }
  
  // 修改单个行的操作
  function handleUpdateRow(row) {
    // 将选中行的数据复制到表单中进行编辑
    form.value = {...row };
    open.value = true;
    title.value = "修改库存";
  }
  
  // 计算总价的方法
  function calculateTotalPrice(row) {
    if (row.orderDetail && row.orderDetail.purchaseQuantity && row.orderDetail.purchaseUnitPrice) {
      return row.orderDetail.purchaseQuantity * row.orderDetail.purchaseUnitPrice;
    } else {
      return 0;
    }
  }
  
  // 表格选中项变化处理函数（包括复选框和行选择）
  function handleSelectionChange(selection) {
    selectedInventoryIds.length = 0;
    selectedInventoryIds.push(...selection);
  }
  
  // 全选复选框变化处理函数
  function handleCheckboxAllChange(val) {
    inventoryList.value.forEach(row => {
      row.$selected = val;
    });
    if (val) {
      // 如果全选，将所有行添加到选中记录数组
      selectedInventoryIds.length = 0;
      selectedInventoryIds.push(...inventoryList.value);
    } else {
      // 如果取消全选，清空选中记录数组
      selectedInventoryIds.length = 0;
    }
  }
  
  getList();
  </script>